package game.controller;

import game.environments.GameEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
import javax.swing.Timer;
import listener.KeyboardListener;
import view.ViewController;


public class GameController {
    private List<GameEnvironment> myGameEnvironments;
    private ViewController myViewController;
    private KeyboardListener myKeyboardListener;
    private Timer myTimer;
    private static final int ONE_SECOND = 1000;
    private static final int FRAMES_PER_SECOND = 25;
    private GameEnvironment currentgameEnv;

    public GameController () {
        myGameEnvironments = new LinkedList<GameEnvironment>();
        // create timer to drive the animation--timer prompts actionPerformed
    }

    private void initTimer () {
        myTimer = new Timer(ONE_SECOND / FRAMES_PER_SECOND, new ActionListener() {
            @Override
            public void actionPerformed (ActionEvent e) {
                currentgameEnv.update((double) FRAMES_PER_SECOND / ONE_SECOND);
                currentgameEnv.keyInputPort(myKeyboardListener.getLastKeyPressed());
                myViewController.paint(currentgameEnv);
            }
        });
    }

    public void start () {
        myTimer.start();
    }

    // use to stop or pause the game
    public void stop () {
        myTimer.stop();
    }

    public void add (ViewController vc) {
        myViewController = vc;
    }

    public boolean add (GameEnvironment ge) {
        return ((LinkedList<GameEnvironment>) myGameEnvironments).offer(ge);
    }

    public void add (KeyboardListener keyboardListener) {
        myKeyboardListener = keyboardListener;
        myViewController.addKeyboardListener(myKeyboardListener);
    }

    public void run () {
        while (((LinkedList<GameEnvironment>) myGameEnvironments).peek() != null) {

            currentgameEnv = ((LinkedList<GameEnvironment>) myGameEnvironments).poll();
            initTimer();
            myViewController.paint(currentgameEnv.getSplashScreen());
            try {
                Thread.sleep(3000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            start();
            while (!currentgameEnv.isOver()) {
            }
            stop();
        }
    }

}
